import { OnInit, Component, ViewChild } from '@angular/core';
import { SettingsService, _HttpClient } from '@delon/theme';
import {
  NzFormatEmitEvent,
  NzTreeNode,
  NzMessageService,
  NzNotificationService,
  NzModalService,
  NzModalRef,
} from 'ng-zorro-antd';
import { replaceKeysDeep } from '@shared';
import { SFComponent, SFSchema } from '@delon/form';
import { STColumn, STData, STComponent } from '@delon/abc';
import { PermissionModalComponent } from './edit/permission-modal.component';

@Component({
  selector: 'menu-basic',
  templateUrl: './menu-basic.component.html',
})
export class MenuBasicComponent implements OnInit {
  constructor(
    private settings: SettingsService,
    public http: _HttpClient,
    private msg: NzMessageService,
    private notice: NzNotificationService,
    private confirmServ: NzModalService,
  ) {}
  menu: { [key: string]: any } = {};
  loading = false;
  loading2 = false;
  loading3 = false;
  searchValue = '';
  // 权限列表
  authList = [];
  // 菜单树节点
  nodes = [];
  // 节点树映射
  mapShortToLong = {
    id: 'key',
    name: 'title',
  };
  // 编辑开关
  editSwitch = false;
  addSwitch = false;

  // 表示当前节点
  activedNode: NzTreeNode;
  @ViewChild('sf', { static: false }) sf: SFComponent;

  auth_btn_add = false;
  auth_btn_edit = false;
  auth_btn_del = false;

  columns: STColumn[] = [
    { title: '名称', index: 'name' },
    { title: '编码', index: 'code' },
    { title: '描述', index: 'description' },
    {
      title: '操作',
      buttons: [
        {
          text: '修改',
          type: 'modal',
          modal: {
            component: PermissionModalComponent,
            paramsName: 'record',
          },
          click: (record: STData, modal?: any, instance?: STComponent) => {
            this.loadPermission(this.activedNode.key);
          },
          iif: (item: STColumn) => this.auth_btn_edit,
        },
        {
          text: '删除',
          type: 'del',
          pop: {
            title: '确定删除按钮？',
            okType: 'danger',
          },
          click: (record, _modal, comp) => {
            this.http.delete(`/cf/admin/menu/${record.id}`).subscribe(res => {
              if (res.status === 200) {
                this.notice.success('成功', `成功删除【${record.name}】`);
                this.loadPermission(this.activedNode.key);
              }
            });
          },
          iif: (item: STColumn) => this.auth_btn_del,
        },
      ],
    },
  ];

  schema: SFSchema = {
    properties: {
      type: {
        type: 'string',
        title: '菜单类型',
        default: '0',
        ui: {
          hidden: true,
        },
      },
      menuId: {
        type: 'string',
        title: '菜单id',
        ui: {
          hidden: true,
        },
      },
      delFlag: {
        type: 'string',
        title: '状态',
        ui: {
          hidden: true,
        },
      },
      parentId: {
        type: 'string',
        title: '父级节点',
        readOnly: true,
      },
      name: {
        type: 'string',
        title: '标题',
        readOnly: true,
        ui: {
          placeholder: '标题',
        },
      },
      path: {
        type: 'string',
        title: '路径',
        readOnly: true,
        ui: {
          placeholder: '路径',
        },
      },
      icon: {
        type: 'string',
        title: '图标',
        readOnly: true,
        ui: {
          placeholder: '图标',
        },
      },
      sort: { type: 'number', title: '排序', readOnly: true, default: 1 },
    },
    required: ['name'],
  };

  ngOnInit() {
    this.auth_btn_add = this.settings.user.permissions.sys_menu_add;
    this.auth_btn_edit = this.settings.user.permissions.sys_menu_edit;
    this.auth_btn_del = this.settings.user.permissions.sys_menu_del;
    this.loadMenuTree();
  }

  /**
   * 保存菜单信息
   * @param value
   */
  sfSubmit(value: any) {
    if (this.editSwitch) {
      this.http.put(`/cf/admin/menu`, value).subscribe(res => {
        if (res.status === 200) {
          this.notice.success('提示', '操作成功');
          this.menu = null;
          this.activedNode = null;
          this.loadMenuTree();
          this.closeEdit();
        }
      });
    } else {
      this.http.post(`/cf/admin/menu`, value).subscribe(res => {
        if (res.status === 200) {
          this.notice.success('提示', '操作成功');
          this.menu = null;
          this.activedNode = null;
          this.loadMenuTree();
          this.closeAddG();
        }
      });
    }
  }

  /**
   * 加载菜单树
   */
  loadMenuTree() {
    this.loading = true;
    this.http.get(`/cf/admin/menu/tree?type=0`).subscribe(res => {
      if (res.status === 200) {
        this.nodes = [];
        const o: [] = replaceKeysDeep(res.data, this.mapShortToLong);
        o.forEach(r => {
          this.nodes.push(r);
        });
      }
      this.loading = false;
    });
  }

  loadPermission(parentId) {
    this.loading3 = true;
    this.http.get(`/cf/admin/menu/tree?parentId=${parentId}&type=1`).subscribe(res => {
      if (res.status === 200) {
        this.authList = res.data;
      }
      this.loading3 = false;
    });
  }

  /**
   * 加载菜单明细
   * @param menuId
   */
  getMenu(menuId) {
    this.loading2 = true;
    this.http.get(`/cf/admin/menu/${menuId}`).subscribe(res => {
      if (res.status === 200) {
        this.menu = res.data;
        this.refreshMenuSchema();
      }
      this.loading2 = false;
    });
  }

  private setValue() {
    if (this.menu) {
      this.schema.properties.menuId.default = this.menu.menuId;
      this.schema.properties.delFlag.default = this.menu.delFlag;
      this.schema.properties.parentId.default = this.menu.parentId;
      this.schema.properties.name.default = this.menu.name;
      this.schema.properties.path.default = this.menu.path;
      this.schema.properties.icon.default = this.menu.icon;
      this.schema.properties.sort.default = this.menu.sort;
    }
  }
  private setValue2() {
    this.reset();
    if (this.menu) {
      this.schema.properties.parentId.default = this.menu.menuId;
    }
  }

  private reset() {
    this.schema.properties.menuId.default = null;
    this.schema.properties.delFlag.default = '0';
    this.schema.properties.parentId.default = '-1';
    this.schema.properties.name.default = null;
    this.schema.properties.path.default = null;
    this.schema.properties.icon.default = null;
    this.schema.properties.sort.default = 1;
  }

  refreshMenuSchema() {
    if (this.menu) {
      this.setValue();
    } else {
      this.reset();
    }
    this.sf.refreshSchema();
  }

  resetMenuSchema() {
    this.reset();
    this.sf.refreshSchema();
  }
  // 切换表单读写状态
  switchState(state) {
    this.schema.properties.menuId.readOnly = state;
    this.schema.properties.delFlag.readOnly = state;
    this.schema.properties.name.readOnly = state;
    this.schema.properties.path.readOnly = state;
    this.schema.properties.icon.readOnly = state;
    this.schema.properties.sort.readOnly = state;
    this.sf.refreshSchema();
  }

  /**
   * 点击编辑按钮
   */
  statEdit() {
    this.closeAddG();
    if (!this.activedNode || !this.menu) {
      this.msg.warning('请选择一个菜单');
      return;
    }
    this.setValue();
    this.editSwitch = true;
    this.switchState(false);
  }
  /**
   * 点击关闭编辑
   */
  closeEdit() {
    this.editSwitch = false;
    this.refreshMenuSchema();
    this.switchState(true);
  }
  /**
   * 添加菜单组/菜单
   */
  startAddG(t) {
    this.closeEdit();
    if (t === 0) {
      this.reset();
    } else {
      if (this.menu && this.menu.parentId !== '-1') {
        this.msg.error('只支持2级菜单');
        return;
      }
      this.setValue2();
    }
    this.switchState(false);
    this.sf.refreshSchema();
    this.addSwitch = true;
  }

  /**
   * 关闭添加菜单组
   */
  closeAddG() {
    this.addSwitch = false;
    this.resetMenuSchema();
    this.switchState(true);
  }

  /**
   * 删除菜单
   */
  delMenu() {
    if (this.activedNode) {
      this.confirmServ.confirm({
        nzTitle: `确定删除【${this.activedNode.origin.title}】?`,
        nzOnOk: () => {
          this.http.delete(`/cf/admin/menu/${this.activedNode.key}`).subscribe(res => {
            if (res.status === 200) {
              this.notice.success('成功', '操作成功');
              this.loadMenuTree();
              this.menu = null;
              this.activedNode = null;
              this.editSwitch = false;
              this.addSwitch = false;
              this.authList = [];
              this.switchState(true);
              this.resetMenuSchema();
            }
          });
        },
      });
    }
  }

  nzEvent(event: NzFormatEmitEvent): void {
    if (event.eventName === 'click') {
      this.editSwitch = false;
      this.addSwitch = false;
      this.resetMenuSchema();
      this.switchState(true);
      if (event.node.isSelected) {
        this.getMenu(event.node.key);
        this.loadPermission(event.node.key);
        this.activedNode = event.node!;
      } else {
        this.menu = null;
        this.activedNode = null;
        this.authList = [];
      }
    }
  }

  /**
   * 添加按钮
   */
  addPermission() {
    if (this.activedNode) {
      if (this.activedNode.origin.parentId === '-1') {
        this.msg.warning('菜单组不能添加按钮');
        return;
      }
      const modal: NzModalRef = this.confirmServ.create({
        nzContent: PermissionModalComponent,
        nzComponentParams: { parent: this.activedNode.origin },
        nzFooter: null,
      });
      modal.afterClose.subscribe(res => {
        if (res) {
          this.loadPermission(this.activedNode.key);
        }
      });
    } else {
      this.msg.warning('请先选择一个菜单');
    }
  }
}
